package com.bookseek.xreader.demo.com.jieba;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;


import com.bookseek.xreader.R;
import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.consts.XreaderHolder;
import com.bookseek.xreader.params.ExtraParams;
import com.bookseek.xreader.po.TMetaPo;
import com.bookseek.xreader.service.DataService;
import com.bookseek.xreader.service.dk.BdocService;
import com.bookseek.xreader.service.dk.FtsBookService;
import com.bookseek.xreader.service.dk.TMetaService;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.views.SearchContentActivity;
import com.bookseek.xreader.views.SlideSearchActivity;
import com.bookseek.xreader.views.reader.BookReaderActivity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import jackmego.com.jieba_android.JiebaSegmenter;

public class MainActivity extends AppCompatActivity {


    private Button test_db,
            test_jieba,
            test_cfg,
            test_down_git,
            test_fts5,
            test_search,
            test_slide,
            test_dianji,
            test_reader,
            test_bookfts,
            test_down_ynote;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        DLog.info("MainActivity============> onCreate");
        observeWorkStatus(XreaderHolder.SHICI_ID);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_jieba);
        test_db = findViewById(R.id.test_db);
        test_slide = findViewById(R.id.test_slide);
        test_dianji = findViewById(R.id.test_dianji);
        test_reader = findViewById(R.id.test_reader);
        test_bookfts = findViewById(R.id.test_bookfts);

        test_fts5 = findViewById(R.id.test_fts5);
        test_search  = findViewById(R.id.test_search);
        test_down_ynote = findViewById(R.id.test_down_ynote);
        test_down_git = findViewById(R.id.test_down_git);
        test_cfg = findViewById(R.id.test_cfg);
        test_jieba = findViewById(R.id.test_jieba);
        editText = findViewById(R.id.editText);
        Context context = this;

        test_bookfts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DLog.info("test_bookfts");

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //6641969
                String api = "https://share.note.youdao.com/yws/public/resource/6f7dfb85ac26f0c5010bf6ff7fb7ef9c/xmlnote/7F28FE569CB24A1A9D694F2C6065FFD8/6446";
                Map<String,Long> tmMap = new HashMap<>();
                ExtraParams extra = new ExtraParams();
                OkHttpUtils.getInstance().addSingleTask(api, baos, new OkHttpUtils.DownloadCallback() {
                    @Override
                    public void onStart(String fileUrl,ExtraParams params) {
                        DLog.info("开始下载==》",fileUrl);
                        tmMap.put("startTm", System.currentTimeMillis());
                    }
                    @Override
                    public void onProgress(String fileUrl, int progress,ExtraParams params) {
                        DLog.info("下载进度==》",progress);
                    }
                    @Override
                    public void onSuccess(String fileUrl, ByteArrayOutputStream writeOs,ExtraParams params) {
                        byte[] bytes = writeOs.toByteArray();
                        int len = bytes.length;
                        Long endTm = System.currentTimeMillis();
                        Long startTm = tmMap.get("startTm");
                        Long dur = endTm-startTm;
                        DLog.info("下载成功==》",fileUrl," 数据大小",len," 耗时：",dur," ms");
                        //后台线程处理
                        FtsBookService.getInstance().dealDownDataAsync(new TMetaPo(),bytes);
                    }
                    @Override
                    public void onFailure(String fileUrl, String errorMsg,ExtraParams params) {
                        DLog.error("下载失败==》",fileUrl,errorMsg);
                    }
                },extra);


//                Intent intent = new Intent(context, BookReaderActivity.class);
//                //汉书10391
//                intent.putExtra("bookid",10391L);
//                startActivity(intent);
            }
        });

        test_reader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DLog.info("test_reader click");
                Intent intent = new Intent(context, BookReaderActivity.class);
                //汉书10391
                intent.putExtra("bookid",9103L);
                startActivity(intent);
            }
        });


        //test_slide
        test_slide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DLog.info("Slide Search click");
                Intent intent = new Intent(context, SlideSearchActivity.class);
                intent.putExtra("btype",XreaderConts.BTYPE_SHICI);
                startActivity(intent);
            }
        });
        //test_dianji
        test_dianji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DLog.info("test_dianji Search click");
                Intent intent = new Intent(context, SlideSearchActivity.class);
                intent.putExtra("btype",XreaderConts.BTYPE_DIANJI);
                startActivity(intent);
            }
        });
        //test_search
        test_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, SearchContentActivity.class);
                startActivity(intent);
            }
        });
        //测试fts5 查询耗时
        test_fts5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BdocService.getInstance().testQueryTime();
            }
        });
        //测试结巴分词
        test_jieba.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<String> wordList = JiebaSegmenter.getJiebaSegmenterSingleton().getDividedStringIndex(editText.getText().toString());
                Log.i(XreaderConts.TAG,String.join("\n",wordList));
            }
        });

        //测试数据库
        test_db.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(XreaderConts.TAG,"测试DB");
            }
        });

        //测试cfg
        test_cfg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(XreaderConts.TAG,"测试app cfg");
                DataService.getInstance().initAppCfg(cfg->{
                    Log.i(XreaderConts.TAG,"CFG=>"+ OkHttpUtils.gson.toJson(cfg));
                    TMetaService.getInstance().saveTMetaInfo(cfg);
                });
            }
        });
        //测试ynote 下载
        test_down_ynote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(XreaderConts.TAG,"测试test_down_ynote");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //6641969
                String api = "https://note.youdao.com/yws/public/resource/bbf679ba87130d49b5237fa99266af9e/xmlnote/7CAB1386955F4B18A7C0C8B0D8561D1C/5971";
                api = "https://note.youdao.com/yws/public/resource/bbf679ba87130d49b5237fa99266af9e/xmlnote/F96F688D912D464884B154BF3607D967/6015";
                //13745029
                api = "https://note.youdao.com/yws/public/resource/bbf679ba87130d49b5237fa99266af9e/xmlnote/B667217A6DA545EF8BB09835B39E3A02/5987";
                Map<String,Long> tmMap = new HashMap<>();
                ExtraParams extra = new ExtraParams();
                OkHttpUtils.getInstance().addSingleTask(api, baos, new OkHttpUtils.DownloadCallback() {
                    @Override
                    public void onStart(String fileUrl,ExtraParams params) {
                        DLog.info("开始下载==》",fileUrl);
                        tmMap.put("startTm", System.currentTimeMillis());
                    }
                    @Override
                    public void onProgress(String fileUrl, int progress,ExtraParams params) {
                        DLog.info("下载进度==》",progress);
                    }

                    @Override
                    public void onSuccess(String fileUrl, ByteArrayOutputStream writeOs,ExtraParams params) {
                        byte[] bytes = writeOs.toByteArray();
                        int len = bytes.length;
                        Long endTm = System.currentTimeMillis();
                        Long startTm = tmMap.get("startTm");
                        Long dur = endTm-startTm;
                        DLog.info("下载成功==》",fileUrl," 数据大小",len," 耗时：",dur," ms");
                        //后台线程处理
                        BdocService.getInstance().dealDownDataAsync(new TMetaPo(),bytes);
                    }

                    @Override
                    public void onFailure(String fileUrl, String errorMsg,ExtraParams params) {
                        DLog.error("下载失败==》",fileUrl,errorMsg);
                    }
                },extra);
            }
        });

        //测试git下载
        test_down_git.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(XreaderConts.TAG,"测试test_down_git");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //6986649
                String api = "https://fastly.jsdelivr.net/gh/lxlolo/nlp01@main/sc/shici_001.js";
                api = "https://gcore.jsdelivr.net/gh/lxlolo/nlp01@main/sc/shici_001.js";
                api = "https://pdf1.webgetstore.com/2025/08/21/1cd12a334a44f4a724fb807751275f0d.txt?sg=c9a435f441cec2bd36885d7b54e160b2&e=68a684f9&fileName=shici_001.txt&fi=250389263";
                Map<String,Long> tmMap = new HashMap<>();
                ExtraParams extra = new ExtraParams();
                OkHttpUtils.getInstance().addSingleTask(api, baos, new OkHttpUtils.DownloadCallback() {
                    @Override
                    public void onStart(String fileUrl, ExtraParams params) {
                        DLog.info("开始下载==》",fileUrl);
                        tmMap.put("startTm", System.currentTimeMillis());
                    }
                    @Override
                    public void onProgress(String fileUrl, int progress, ExtraParams params) {
                        DLog.info("下载进度==》",progress);
                    }

                    @Override
                    public void onSuccess(String fileUrl, ByteArrayOutputStream writeOs,ExtraParams params) {
                        byte[] bytes = writeOs.toByteArray();
                        int len = bytes.length;
                        Long endTm = System.currentTimeMillis();
                        Long startTm = tmMap.get("startTm");
                        Long dur = endTm-startTm;
                        DLog.info("下载成功==》",fileUrl," 数据大小",len," 耗时：",dur," ms");
                    }

                    @Override
                    public void onFailure(String fileUrl, String errorMsg,ExtraParams params) {
                        DLog.error("下载失败==》",fileUrl,errorMsg);
                    }
                },extra);
            }
        });

    }

    private void observeWorkStatus(UUID workId) {
        if(workId == null){
            return;
        }
        DLog.info("observeWorkStatus======>",workId.toString());
        // 通过ID获取任务信息的LiveData
        WorkManager.getInstance(this)
                .getWorkInfoByIdLiveData(workId)
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        if (workInfo == null) {
                            DLog.info("任务信息为空",workId);
                            return;
                        }

                        // 根据任务状态更新UI
                        switch (workInfo.getState()) {
                            case ENQUEUED:
                                DLog.info("任务已入队，等待执行...",workId);
                                break;
                            case RUNNING:
                                DLog.info("任务正在执行中...");
                                break;
                            case SUCCEEDED:
                                // 任务成功，可获取返回结果
//                                String result = workInfo.getOutputData()
//                                        .getString(MyWorker.RESULT_KEY);
                                DLog.info("任务执行成功: ",workId);
                                break;
                            case FAILED:
                                DLog.info("任务执行失败");
                                break;
                            case CANCELLED:
                                DLog.info("任务已取消");
                                break;
                            default:
                                DLog.info("状态: " + workInfo.getState().name());
                        }
                    }
                });
    }
}
